package org.cicd.utils

import org.cicd.enums.EnvInfoType


/**
 * 清理当前工程的目录
 * @return
 */
def clearSpace(list=['jar','zip'],path) {
    list.each {
        sh "find ./ -type f -name *.$it | xargs rm -rf"
    }
    deleteFile("${path}/files/*")
}

/**
 * 格式化输出
 * @param value
 * @param color
 * @return
 */
def printMessage(value, color) {
    def BLACK = "\033[1;30m"
    def RED = "\033[1;31m"
    def GREEN = "\033[1;32m"
    def YELLOW = "\033[1;33m"
    def BLUE = "\033[1;34m"
    def PURPLE = "\033[1;35m"
    def PINK = "\033[1;36m"
    def WHITE = "\033[1;37m"
    def END = "\033[0m"

    def colors = ['groovy': "\033[40;31m >>>>>>>>>>>${value}<<<<<<<<<<< \033[0m",
                  'blue'  : "\033[47;34m ${value} \033[0m",
                  'red'  : "\033[1;31m ${value} \033[0m",
                  'yellow'  : "\033[1;33m ${value} \033[0m",
                  'green2'  : "\033[1;32m ${value} \033[0m",
                  'green' : "[1;32m>>>>>>>>>>${value}>>>>>>>>>>[m",
                  'green1': "\033[40;32m >>>>>>>>>>>${value}<<<<<<<<<<< \033[0m"]
    ansiColor('xterm') {
        println(colors[color])
    }
}

def printInfoMessage(value) {
    printMessage(value, "blue")
}

def printWarningMessage(value) {
    printMessage(value, "yellow")
}
def printErrorMessage(value) {
    printMessage(value, "red")
}
/**
 * 创建临时目录
 * @return
 */
def initTmpDir(path) {
    println("初始化临时目录")
    sh """
        if [ ! -d "${path}" ]; then
                echo "创建文件夹"
                mkdir -p "${path}"
        fi
    """
}

def getGitBranchName() {
    return scm.branches[0].name
}

def getGitBranchNameWithMulBranch() {
    return "${env.BRANCH_NAME}"
}

/**
 * 检查文件是否存在glob: 'script/*.sh'
 * @param path
 * @return
 */
def checkFileExist(path) {
    def files = findFiles(glob: "${path}")
    println("${files}")
    if (null != files && files.length >= 1) {
        return true
    }
    return false
}

def fileExist(filePath) {
    File file = new File(filePath)
    return file.exists()
}

/**
 * 删除文件
 * @param path
 * @return
 */
def deleteFile(path) {
    println("删除文件$path")
    sh """
    rm  -rf ${path}
    """
}


def zipFile(path, fileName) {
    zip dir: "${path}", glob: '', zipFile: "${fileName}"
}

//封装HTTP
def HttpReq(serverName, reqType, reqUrl, reqBody, auth) {
    println("reqBody:" + JsonOutput.toJson(reqBody))
    result = httpRequest authentication: auth,
            httpMode: reqType,
            contentType: "APPLICATION_JSON",
            consoleLogResponseBody: true,
            ignoreSslErrors: true,
            requestBody: JsonOutput.toJson(reqBody),
            url: "${serverName}/${reqUrl}"
    return result
}



def getZipPackageGitReposity(EnvInfoType envInfoType) {

    def utils = new utils()
    def cfg = utils.loadPipelineCfg();
    def paramMap = [:].plus(cfg)

    def repository_url = ""
    switch (envInfoType) {
        case EnvInfoType.dev: // 持续集成开发环境
        case EnvInfoType.test: // 持续集成测试环境
        case EnvInfoType.sit: // 系统集成环境
        case EnvInfoType.staging: // 预发环境
            repository_url = paramMap.get("dev_repository_url")
            break
        case EnvInfoType.uat: // 用户可接受性测试环境-生产灰度
        case EnvInfoType.pro: // 生产环境
        case EnvInfoType.dr:  // 备灾环境
            repository_url = paramMap.get("pro_repository_url")
            break
    }
    return repository_url
}


/**
 * 加载properties.
 * @param filePath properties文件路径.
 * @return props Properties
 * */
def loadProps(String filePath) {
    File propFile = new File(filePath)
    def props = new Properties()
    props.load(propFile.newDataInputStream())
    return props
}

/**
 * 需要插件 安装Pipeline Utility Steps插件
 *
 * @param properties_file
 * @return
 */
def loadProperties(properties_file) {
    def props = readProperties interpolates:true, file:  properties_file
    return props;
}

def loadMavenPom(pom_file) {
    def pom = readMavenPom file: pom_file
    return pom;
}

def loadJson(json_file) {
    def prop = readJSON file: json_file
    return prop;
}

def loadPipelineCfg() {
    def cfg_text = libraryResource("pipelineCfg.yaml")
    def cfg = readYaml text: cfg_text  //pipeline utility steps 插件
    return cfg;
}

def getGitRepUrl() {
    def repositoryUrl = scm.userRemoteConfigs[0].url
    return repositoryUrl;
}

def getSvnRepUrl() {
    def repositoryUrl = scm.locations[0].remote
    return  repositoryUrl;
}

def getFileSeparator() {
    return System.getProperty("file.separator");
}

def isWindows() {
    return System.getProperty("os.name").toLowerCase().indexOf("windows")>=0;
}

def isLinux() {
    return System.getProperty("os.name").toLowerCase().indexOf("linux")>=0;
}

def exeShell(exe_cmd) {
    def statusCode = ''
    try{
        if(isWindows()) {
            statusCode =   bat exe_cmd
        } else {
            statusCode =  sh exe_cmd
        }
    } catch (error){
        printErrorMessage  "status code ${statusCode}"
    }

}

def cp(sourcePath, destPath) {
    def fileOperations = new FileOperations();
    fileOperations.copyFile(sourcePath, destPath)
}

